package no.ntnu.fp.server;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.LinkedList;
import java.util.List;

import no.ntnu.fp.net.co.MessageListener;
import no.ntnu.fp.net.co.MessageReceiver;

public class ConnectionHandler implements MessageListener {
	
	private Socket socket;
	private Server server;
	private StringBuilder messageBuilder;
	private DataOutputStream out;
	
	public ConnectionHandler(Socket socket, Server server) {
		
		this.socket = socket;
		this.server = server;
		messageBuilder = new StringBuilder(/*1024*/);
		
		try {
			out = new DataOutputStream(socket.getOutputStream());
		} catch (IOException e) {
			System.err.println("IOException on socket outputstream");
		}
		
		new Thread(new MessageReceiver(socket, this)).start();
	}

	public void send(String data) {
		System.out.println("Sending to client");
		try {
			out.writeBytes(data+"\n");
		} catch (IOException e) {
			System.err.println("Failed to send to client");
		}
	}

	public void messageReceived(String message) {
		
		messageBuilder.append(message);

		if (message.endsWith("</superpakke>")) {
			server.dataFromClient(message, this);
			messageBuilder = new StringBuilder(/*1024*/);
		}
	}
}
